/**
 * Location view uses a carousel widget to show a list of countries and a list of cities.
 * The countries list shown first. After selecting a country the cities list is shown and populated.
 */

(function() {
	var view = View("location-view");

	qype.views.locationView = view;

	var locationCarousel;
	var quickList;
	var countryList;
	var countryLoading;
	var cityList;
	var cityLoading;
	
	var links;
	
	var countryBackId = "country-back";
	var cityBackId = "city-back";
	
	view.getHtml = function() {
		return sprintf('<div id="%s"><h1>%s</h1></div>', view.getId(), qype.strings.location);
	};
	
	view.init = function(onLocationChangeFunction) {
		this.initBack();
		this.onLocationChange = onLocationChangeFunction;
		locationCarousel = CarouselWidget();
		view.getContainer().append(locationCarousel.getHtml());
		quickList = ListWidget();
		locationCarousel.addView(quickList.getHtml());
		countryList = ListWidget();
		countryLoading = LoadingWidget({label: qype.strings.loading});
		countryHtml = [
			sprintf('<h2>%s</h2>', qype.strings.country),
			countryList.getHtml(),
			countryLoading.getHtml()
		];
		this.addBack(countryBackId, quickList.showMwl() + locationCarousel.linkMwl(0) + countryList.hideMwl() + this.showBackMwl());
		locationCarousel.addView(countryHtml.join(''));
		countryList.hide();
		cityList = ListWidget();
		cityLoading = LoadingWidget({label: qype.strings.loading});
		var cityHtml = [
			sprintf('<h2>%s</h2>', qype.strings.city),
			cityList.getHtml(),
			cityLoading.getHtml()
		];
		this.addBack(cityBackId, countryList.showMwl() + locationCarousel.linkMwl(1) + cityList.hideMwl() + cityLoading.showMwl() + this.showBackMwl(countryBackId));
		locationCarousel.addView(cityHtml.join(''));
		cityList.hide();
	}
	
	view.setLinks = function(l) {
		links = l;
	};
	
	function entriesToListItems(entries, onclickTemplate, sort) {
		var results = $.map(entries, function(item, index) {
			return {
				onclick: sprintf(onclickTemplate, item.locator.domain_id, item.locator.title.value),
				name: item.locator.title.value
			};
		});
		if(sort) {
			results.sort(function(a, b) {
				return (a.name > b.name) - (a.name < b.name);
			});
		}
		return results;
	}
	
	view.populateQuickList = function() {
		quickList.populate([
			{
				onclick: links.places + "qype.views.locationView.onLocationChange.call(qype.views.locationView, 'uki', 'London');",
				name: "London"
			},
			{
				onclick: links.places + "qype.views.locationView.onLocationChange.call(qype.views.locationView, 'de300-berlin', 'Berlin');",
				name: "Berlin"
			},
			{
				onclick: this.showBackMwl(countryBackId) + countryLoading.showLoadingMwl() + countryList.showMwl() + locationCarousel.linkMwl(1) + "qype.views.locationView.loadCoutries.call(qype.views.locationView);",
				name: qype.strings.otherPlaces
			}
		]);
	};
	
	view.loadCoutries = function() {
		if (countryList.size() > 0) return;
		countryList.populate([]);
		qype.API.get('locators', {
	        onSuccess: function(response) {
				var onclickTemplate = [
					view.showBackMwl(cityBackId),
					cityLoading.showLoadingMwl(),
					cityLoading.showMwl(),
					locationCarousel.linkMwl(2),
					countryList.hideMwl(),
					"qype.views.locationView.loadCities.call(qype.views.locationView, '%s', '%s');"
				];
				countryList.populate(entriesToListItems(response.results, onclickTemplate.join(""), true));
				countryList.show();
				countryLoading.hide();
	        },
	        onFailure: function(response, status) {
				countryList.populate([]);
				countryList.hide();
				countryLoading.setError(util.networkErrorMessage(status, countryList.hideMwl() + countryLoading.showLoadingMwl() + "qype.views.locationView.loadCoutries.call(qype.views.locationView);"));
				countryLoading.showError();
				countryLoading.show();
	        }
		});
	};

	view.loadCities = function(country) {
		function getCities(entries, total, page) {
			if(total < 0 || entries.length < Math.min(20, total)) {
				qype.API.get('locators', {
			        onSuccess: function(response, text) {
						if(total < 0) total = response.total_entries;
						getCities(entries.concat(response.results), total, page + 1);
			        },
			        onFailure: function(response, status) {
						cityList.populate([]);
						cityList.hide();
						cityLoading.setError(util.networkErrorMessage(status, cityList.hideMwl() + cityLoading.showLoadingMwl() + sprintf("qype.views.locationView.loadCities.call(qype.views.locationView, '%s');", country)));
						cityLoading.showError();
						cityLoading.show();
			        }
				}, country + "/children", {page: page});
			} else {
				var onclickTemplate = [
					links.places,
					"qype.views.locationView.onLocationChange.call(qype.views.locationView, '%s', '%s');"
				];
				cityList.populate(entriesToListItems(entries, onclickTemplate.join("")));
				cityList.show();
				cityLoading.hide();
				if(entries.length < total) {
					// TODO add load more link
				}
			}
		}
		
		cityList.populate([]);
		if(!country) return;
		getCities([], -1, 1);
	};
	
	view.resetMwl = function() {
		return locationCarousel.linkMwl("0", true) + quickList.showMwl() + countryList.hideMwl() + countryLoading.showLoadingMwl() + cityList.hideMwl() + cityLoading.showLoadingMwl() + cityLoading.showMwl() + this.showBackMwl(); 
	};
})();
